package com.szwistar.common.algorithm;

public class Hash {
	
	public static int ELFHash(byte[] str) {
	   int hash = 0;
	   int x    = 0;

	   for(int i = 0; i < str.length; i++) {
	      hash = (hash << 4) + str[i];
	      if((x = (int) (hash & 0xF0000000L)) != 0) {
	         hash ^= (x >> 24);
	      }
	      hash &= ~x;
	   }

	   return hash;
	}
	
	public static int SDBMHash(byte[] str) {
	   int hash = 0;

	   for(int i = 0; i < str.length; i++) {
	      hash = str[i] + (hash << 6) + (hash << 16) - hash;
	   }

	   return hash;
	}
	
	public static int DJBHash(byte[] str) {
	   int hash = 5381;

	   for(int i = 0; i < str.length; i++) {
	      hash = ((hash << 5) + hash) + str[i];
	   }

	   return hash;
	}
	
	public static byte[] makeHash(byte[] src) {
		int h1 = ELFHash(src);
		int h2 = SDBMHash(src);
		int h3 = DJBHash(src);
		System.out.println("elf=" + h1 + ", sdb=" + h2 + ", djb=" + h3);
		byte[] out = new byte[12];
		out[0] = (byte) (h1 & 0xff);// 最低位   
		out[1] = (byte) ((h1 >> 8) & 0xff);// 次低位   
		out[2] = (byte) ((h1 >> 16) & 0xff);// 次高位   
		out[3] = (byte) (h1 >>> 24);// 最高位,无符号右移
		out[4] = (byte) (h2 & 0xff);// 最低位   
		out[5] = (byte) ((h2 >> 8) & 0xff);// 次低位   
		out[6] = (byte) ((h2 >> 16) & 0xff);// 次高位   
		out[7] = (byte) (h2 >>> 24);// 最高位,无符号右移
		out[8] = (byte) (h3 & 0xff);// 最低位   
		out[9] = (byte) ((h3 >> 8) & 0xff);// 次低位   
		out[10] = (byte) ((h3 >> 16) & 0xff);// 次高位   
		out[11] = (byte) (h3 >>> 24);// 最高位,无符号右移
		
		return out;
	}
}
